﻿namespace EasyToolkit.BindingTemplates.Views
{
    using System;
    using EasyToolkit.BindingTemplates.Context;
    using EasyToolkit.BindingTemplates.Definitions;
    using EasyToolkit.BindingTemplates.SortAndFilter;

    public class TemplateView : ITemplateView
    {
        #region attributes and properties
        protected object syncRoot = new object();

        public Guid Ident
        { get; protected set; }

        public ITemplateView Parent
        { get; protected set; }

        public IBindingContext BindingContext
        { get; internal set; }

        public bool IsDisposed
        { get; protected set; }

        public ITemplateDefinition TemplateDefinition
        { get; protected set; }

        public IRootTemplateView RootParent
        { get; protected set; }

        public ISortAndFilter SortAndFilter
        { get; protected set; }
        #endregion
        
        #region .ctors
        public TemplateView(ITemplateView parent, ITemplateDefinition templateDefinition, ISortAndFilter sortAndFilter)
        {
            RootParent = parent == null ? null : parent.RootParent;
            Parent = parent;
            SortAndFilter = sortAndFilter;

            Ident = Guid.NewGuid();
            if (templateDefinition == null)
            {
                string message = "Cannot create a 'view' without a 'template definition'.";
                throw new EasyToolkitException(message);
            }
            TemplateDefinition = templateDefinition;
        }
        #endregion

        public virtual void Dispose()
        {
            lock (syncRoot)
            {
                if (!IsDisposed)
                {
                    if (BindingContext != null)
                        BindingContext.Dispose();
                    BindingContext = null;

                if (!IsDisposed)
                    IsDisposed = true;
                }
            }
        }
    }
}
